<template>
  <div class="payment-confirm-page">
    <!-- 顶部导航 -->
    <van-nav-bar 
      title="支付确认" 
      left-arrow 
      @click-left="goBack"
      :right-text="'100%'"
    />
    
    <!-- 视角切换 -->
    <div class="perspective-tabs">
      <div 
        class="tab-item"
        :class="{ active: currentPerspective === 'seller' }"
        @click="switchPerspective('seller')"
      >
        <van-icon name="home-o" />
        <span>我的销售</span>
      </div>
      <div 
        class="tab-item"
        :class="{ active: currentPerspective === 'buyer' }"
        @click="switchPerspective('buyer')"
      >
        <van-icon name="shopping-cart-o" />
        <span>我的购买</span>
      </div>
    </div>
    
    <!-- 销售统计 -->
    <div class="stats-section">
      <div class="stats-title">{{ currentPerspective === 'seller' ? '销售统计' : '购买统计' }}</div>
      <div class="stats-grid">
        <div class="stats-item">
          <div class="stats-number">{{ stats.pending }}</div>
          <div class="stats-label">待确认</div>
        </div>
        <div class="stats-item">
          <div class="stats-number">{{ stats.confirmed }}</div>
          <div class="stats-label">已确认</div>
        </div>
        <div class="stats-item">
          <div class="stats-number">{{ stats.rejected }}</div>
          <div class="stats-label">已拒绝</div>
        </div>
      </div>
    </div>
    
    <!-- 状态筛选 -->
    <div class="status-tabs">
      <div 
        class="status-tab"
        :class="{ active: currentStatus === 'pending' }"
        @click="switchStatus('pending')"
      >
        待确认
      </div>
      <div 
        class="status-tab"
        :class="{ active: currentStatus === 'confirmed' }"
        @click="switchStatus('confirmed')"
      >
        已确认
      </div>
      <div 
        class="status-tab"
        :class="{ active: currentStatus === 'rejected' }"
        @click="switchStatus('rejected')"
      >
        已拒绝
      </div>
    </div>
    
    <!-- 销售订单 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <div class="orders-section">
        <div class="section-title">{{ currentPerspective === 'seller' ? '销售订单' : '购买订单' }}</div>
        
        <!-- 订单列表 -->
        <van-list
          v-model:loading="loading"
          :finished="!hasMore"
          finished-text="没有更多了"
          @load="loadMore"
        >
          <div 
            v-for="order in paymentList" 
            :key="order.id" 
            class="order-item"
            @click="viewOrderDetail(order.id)"
          >
            <div class="order-main">
              <div class="order-info">
                <div class="product-info">
                  <img 
                    class="product-image" 
                    :src="order.product_image || order.productImage || 'https://via.placeholder.com/80x80'" 
                    alt="商品图片"
                  />
                  <div class="product-details">
                    <div class="product-title">{{ order.product_title || order.productTitle }}</div>
                    <div class="product-price">¥{{ (order.amount || order.totalAmount || 0).toFixed(2) }}</div>
                  </div>
                </div>
                <div class="order-time">{{ formatTime(order.create_time || order.createTime) }}</div>
              </div>
              
              <div class="order-status">
              <div class="status-tag" :class="order.status">
                {{ getStatusText(order.status) }}
                </div>
              </div>
            </div>
            
            <!-- 查看详情按钮 -->
            <div class="order-actions">
                <van-button 
                  type="primary" 
                  size="small"
                @click.stop="viewOrderDetail(order.id)"
                >
                查看详情
                </van-button>
            </div>
          </div>
        </van-list>
        
        <!-- 空状态 -->
        <div v-if="paymentList.length === 0 && !loading" class="empty-state">
          <van-empty description="暂无订单" />
        </div>
      </div>
    </van-pull-refresh>
    
    <!-- 加载状态 -->
    <van-loading v-if="loading && paymentList.length === 0" class="page-loading">
      加载中...
    </van-loading>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { 
  getPaymentList, 
  getPaymentStats
} from '@/api/payment-confirm'

const router = useRouter()
const route = useRoute()

// 响应式数据
const currentPerspective = ref('seller') // seller: 卖家视角, buyer: 买家视角
const currentStatus = ref('pending') // pending: 待确认, confirmed: 已确认, rejected: 已拒绝
const paymentList = ref([])
const stats = ref({
  pending: 0,
  confirmed: 0,
  rejected: 0
})

// 分页相关
const page = ref(1)
const pageSize = ref(20)
const hasMore = ref(true)
const loading = ref(false)
const refreshing = ref(false)

// 切换视角
const switchPerspective = (perspective) => {
  if (perspective === currentPerspective.value) return
  
  currentPerspective.value = perspective
  currentStatus.value = 'pending' // 切换视角时重置为待确认状态
  paymentList.value = []
  page.value = 1
  hasMore.value = true
  
  loadPaymentList(true)
  loadStats()
}

// 切换状态筛选
const switchStatus = (status) => {
  if (status === currentStatus.value) return
  
  currentStatus.value = status
  paymentList.value = []
  page.value = 1
  hasMore.value = true
  
  loadPaymentList(true)
}

// 加载支付确认列表
const loadPaymentList = async (refresh = false) => {
  if (loading.value) return

  try {
    loading.value = true

    const currentPage = refresh ? 1 : page.value
    const params = {
      page: currentPage,
      pageSize: pageSize.value,
      status: currentStatus.value,
      perspective: currentPerspective.value
    }

    console.log('请求参数:', params)
    const result = await getPaymentList(params)
    console.log('支付确认列表响应:', result)

    // 处理后端返回的数据结构，与微信小程序保持一致
    const newList = result.items || []
    console.log('处理后的列表数据:', newList)
    
    if (refresh) {
      paymentList.value = newList
      page.value = 1
      hasMore.value = (result.page || 0) < (result.total_page || 1) - 1
    } else {
      paymentList.value = [...paymentList.value, ...newList]
      page.value = currentPage + 1
      hasMore.value = (result.page || 0) < (result.total_page || 1) - 1
    }
    
    console.log('设置后的paymentList:', paymentList.value)
  } catch (e) {
    console.error('加载支付确认列表失败:', e)
    showToast('加载失败')
  } finally {
    loading.value = false
  }
}

// 加载统计信息
const loadStats = async () => {
  try {
    const result = await getPaymentStats({ perspective: currentPerspective.value })
    // 处理后端返回的统计数据结构
    stats.value = result.data || {
      pending: 0,
      confirmed: 0,
      rejected: 0
    }
  } catch (e) {
    console.error('加载统计信息失败:', e)
  }
}



// 查看订单详情
const viewOrderDetail = (paymentId) => {
  router.push({
    path: '/payment-detail',
    query: { 
      id: paymentId,
      perspective: currentPerspective.value // 传递当前视角
    }
    })
}



// 下拉刷新
const onRefresh = async () => {
  try {
    await loadPaymentList(true)
    await loadStats()
  } finally {
    refreshing.value = false
  }
}

// 加载更多
const loadMore = async () => {
  if (!hasMore.value || loading.value) return
  await loadPaymentList()
}

// 返回上一页
const goBack = () => {
  router.push('/')
}

// 格式化时间
const formatTime = (timestamp) => {
  // 处理时间戳，支持字符串和数字格式
  let date
  if (typeof timestamp === 'string') {
    date = new Date(timestamp)
  } else if (typeof timestamp === 'number') {
    date = new Date(timestamp)
  } else {
    return timestamp || ''
  }
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return timestamp || ''
  }
  
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待确认',
    'confirmed': '已确认',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

// 组件挂载时初始化数据
onMounted(() => {
  loadPaymentList(true)
  loadStats()
})

// 组件卸载时清理
onUnmounted(() => {
  // 清理定时器等资源
})
</script>

<style lang="scss" scoped>
.payment-confirm-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20px;
  
  // 大屏适配
  @media (min-width: 768px) {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px 20px;
  }
  
  @media (min-width: 1024px) {
    max-width: 1400px;
    padding: 0 40px 20px;
  }
  
  @media (min-width: 1440px) {
    max-width: 1600px;
    padding: 0 60px 20px;
  }
}

.perspective-tabs {
  display: flex;
  background: #fff;
  margin-bottom: 10px;
  border-radius: 8px;
  margin: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  @media (min-width: 768px) {
    margin: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  }
  
  .tab-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px 10px;
    cursor: pointer;
    transition: all 0.3s ease;
    
    @media (min-width: 768px) {
      padding: 20px 15px;
      flex-direction: row;
      gap: 10px;
    }
    
    &.active {
      background: #fff;
      color: #333;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      
      @media (min-width: 768px) {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
      }
    }
    
    &:not(.active) {
      background: #f8f9fa;
      color: #666;
    }
    
    .van-icon {
      font-size: 20px;
      margin-bottom: 5px;
      
      @media (min-width: 768px) {
        font-size: 24px;
        margin-bottom: 0;
      }
    }
    
    span {
      font-size: 14px;
      font-weight: 500;
      
      @media (min-width: 768px) {
        font-size: 16px;
      }
    }
  }
}

.stats-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  margin: 10px;
  border-radius: 12px;
  padding: 20px;
  color: #fff;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
  
  @media (min-width: 768px) {
    margin: 20px;
    padding: 30px;
    border-radius: 16px;
  }
  
  .stats-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 20px;
    opacity: 0.9;
    
    @media (min-width: 768px) {
      font-size: 20px;
      margin-bottom: 30px;
    }
  }
  
  .stats-grid {
    display: flex;
    justify-content: space-around;
    
    @media (min-width: 768px) {
      gap: 40px;
    }
    
    .stats-item {
      text-align: center;
      
      .stats-number {
        font-size: 32px;
        font-weight: bold;
        margin-bottom: 8px;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        
        @media (min-width: 768px) {
          font-size: 48px;
          margin-bottom: 12px;
        }
      }
      
      .stats-label {
        font-size: 14px;
        opacity: 0.8;
        
        @media (min-width: 768px) {
          font-size: 16px;
        }
      }
    }
  }
}

.status-tabs {
  display: flex;
  background: #fff;
  margin: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  @media (min-width: 768px) {
    margin: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  }
  
  .status-tab {
    flex: 1;
    text-align: center;
    padding: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-size: 14px;
    position: relative;
    
    @media (min-width: 768px) {
      padding: 16px;
      font-size: 16px;
    }
    
    &.active {
      background: #fff;
      color: #333;
      font-weight: 500;
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 30px;
        height: 2px;
        background: #667eea;
        border-radius: 1px;
        
        @media (min-width: 768px) {
          width: 40px;
          height: 3px;
        }
      }
    }
    
    &:not(.active) {
      background: #f8f9fa;
      color: #666;
    }
  }
}

.orders-section {
  background: #fff;
  margin: 10px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  @media (min-width: 768px) {
    margin: 20px;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  }
  
  .section-title {
    padding: 15px 20px;
    font-size: 16px;
    font-weight: bold;
    color: #333;
    border-bottom: 1px solid #f0f0f0;
    
    @media (min-width: 768px) {
      padding: 20px 30px;
      font-size: 18px;
    }
  }
}

.order-item {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s ease;
  
  @media (min-width: 768px) {
    padding: 25px 30px;
  }
  
  &:hover {
    background-color: #f8f9fa;
  }
  
  &:last-child {
    border-bottom: none;
  }
  
  .order-main {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 15px;
    
    @media (min-width: 768px) {
      margin-bottom: 20px;
    }
  }
  
  .order-info {
    display: flex;
    align-items: flex-start;
    flex: 1;
  }
  
  .product-info {
    display: flex;
    align-items: flex-start;
    margin-right: 20px;
    
    @media (min-width: 768px) {
      margin-right: 30px;
    }
  }
  
  .product-image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    object-fit: cover;
    margin-right: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    @media (min-width: 768px) {
      width: 100px;
      height: 100px;
      margin-right: 20px;
      border-radius: 12px;
    }
  }
  
  .product-details {
    display: flex;
    flex-direction: column;
    flex: 1;
  }
  
  .product-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 8px;
    line-height: 1.4;
    
    @media (min-width: 768px) {
      font-size: 18px;
      margin-bottom: 12px;
    }
  }
  
  .product-price {
    font-size: 18px;
    font-weight: bold;
    color: #ff4d4f;
    margin-bottom: 8px;
    
    @media (min-width: 768px) {
      font-size: 20px;
      margin-bottom: 12px;
    }
  }
  
  .order-time {
    font-size: 14px;
    color: #999;
    margin-top: 5px;
    
    @media (min-width: 768px) {
      font-size: 16px;
    }
  }
  
  .order-status {
    display: flex;
    align-items: center;
    margin-left: 15px;
    
    @media (min-width: 768px) {
      margin-left: 20px;
    }
  }
  
  .status-tag {
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
    border: none;
    min-width: 60px;
    text-align: center;
    
    @media (min-width: 768px) {
      padding: 8px 16px;
      font-size: 14px;
      min-width: 80px;
    }
    
    &.pending {
      background: #1890ff;
      color: #fff;
      box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
    }
    
    &.confirmed {
      background: #52c41a;
      color: #fff;
      box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
    }
    
    &.rejected {
      background: #ff4d4f;
      color: #fff;
      box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
    }
  }
  
  .order-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    
    @media (min-width: 768px) {
      gap: 16px;
    }
    
    .van-button {
      border-radius: 20px;
      font-weight: 500;
      min-width: 80px;
      height: 36px;
      
      @media (min-width: 768px) {
        min-width: 100px;
        height: 40px;
        font-size: 14px;
      }
      
      &.van-button--success {
        background: #52c41a;
        border-color: #52c41a;
        box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
      }
      
      &.van-button--danger {
        background: #ff4d4f;
        border-color: #ff4d4f;
        box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
      }
      
      &.van-button--primary {
        background: #1890ff;
        border-color: #1890ff;
        box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
      }
    }
  }
}

.load-more {
  text-align: center;
  padding: 20px;
  
  @media (min-width: 768px) {
    padding: 30px;
  }
}

.empty-state {
  padding: 40px 20px;
  
  @media (min-width: 768px) {
    padding: 60px 30px;
  }
}

.page-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  
  @media (min-width: 768px) {
    height: 300px;
  }
}
</style> 